var express = require('express');
var router = express.Router();

var ping = require('../modules/HostsManage.js');

/* GET home page. */
router.get('/', function (req, res, next) {
    console.log(ping.getHosts());
    res.render('ping', {title: 'Ping', "ping": ping.getHosts()});
});

router.get('/hosts', function (req, res, next) {
    res.json(ping.getHosts());
});

router.post('/host', function (req, res, next) {
    req.checkBody('domain', 'param domain is empty').notEmpty();
    req.getValidationResult().then(function (result) {
        if (result.isEmpty()) {
            res.json(ping.addHost(req.body.domain, req.body.port));
        } else {
            res.status(400).send('There have been validation errors: ' + result.array());
        }
    });
});

router.put('/host', function (req, res, next) {
    req.checkBody('domain', 'param domain is empty').notEmpty();
    req.getValidationResult().then(function (result) {
        if (result.isEmpty()) {
            res.json(ping.updateHost(req.body.domain, req.body.port));
        } else {
            res.status(400).send('There have been validation errors: ' + result.array());
        }
    });
});

router.get('/time', function (req, res, next) {
    res.render('ping', {title: 'Ping', "ping": ping.getHosts()});
});

module.exports = router;
